package com.fire.communication.common.utils;

import com.fire.communication.model.User;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.Enumeration;

@Component
public class GlobalUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        GlobalUtil.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        return GlobalUtil.getApplicationContext().getBean(clazz);
    }

    protected static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取session操作对象
     *
     * @return session操作对象
     */
    protected static HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 从session中获取登录用户信息
     *
     * @return 用户信息
     */
    public static User getUsers() {
        return (User) getSession().getAttribute("UserObj");

    }

    /**
     * 获取当前登录用户id
     *
     * @return 用户id
     */
    public static String getUserId() {
        return getUsers().getId();
    }


    public static Timestamp getTime() {
        return new Timestamp(System.currentTimeMillis());
    }

    /**
     * 清空系统内所有Session
     */
    public static void removeAllSession() {
        Enumeration em = getSession().getAttributeNames();
        while (em.hasMoreElements()) {
            getSession().removeAttribute(em.nextElement().toString());
        }
    }
}
